export default {

	data() {
		return {
			title: '收银台',
			type: 'goods',
			goodsData: {},
			orderData: {
				pay_money: 0,
				goods_list: [],
				remark: '',
				goods_num: 0,
				card_type: 'oncecard',
				create_time: 0
			},
			isRepeat: false,
			outTradeNo: '',
			hackReset: true,
			pageActive: '' // 记录当前页面活跃值
		};
	},
	onLoad(option) {
		uni.hideTabBar();
		this.orderData.card_type = option.type || 'oncecard';
		if (this.memberInfo) this.type = 'goods';
	},
	onShow() {
		this.orderData.create_time = this.$util.timeFormat(parseInt(new Date().getTime() / 1000));
		this.addKeyDownEvent();
	},
	onHide() {
		this.removeKeyDownEvent();
	},
	methods: {
		init() {
			if (this.siteStore) {
				var pages = getCurrentPages(); // 获取栈实例
				let currentPage = pages[pages.length - 1]['$page']['fullPath']; //当前页面路径(带参数)
				uni.setStorageSync(currentPage, this.siteStore);
			}
			this.hackReset = false;
			this.$nextTick(() => {
				this.hackReset = true;
			});

			if (this.memberInfo) this.type = 'goods';
		},
		showMember() {
			this.pageActive = 'ShowMember';
			if (!this.memberInfo) {
				if (this.$refs.selectMember) this.$refs.selectMember.open(() => {
					this.type = 'member';
					this.pageActive = 'ShowMemberAfter';
				});
			} else {
				this.type = 'member';
				this.pageActive = 'ShowMemberAfter';
			}
		},
		/**
		 * 切换散客
		 */
		replaceMember() {
			if (this.$refs.selectMember) this.$refs.selectMember.memberId = 0;
			this.$store.commit('setMemberInfo', null);
			this.type = 'goods';
		},
		selectGoods(data) {
			if (this.goodsData['sku_' + data.sku_id]) {
				this.goodsData['sku_' + data.sku_id].num += 1;
			} else {
				this.goodsData['sku_' + data.sku_id] = data;
				this.goodsData['sku_' + data.sku_id].num = 1;
			}
			this.pageActive = 'SelectGoodsAfter'; // 记录页面当前活跃值
			this.calculation();
		},
		calculation() {
			if (!Object.keys(this.goodsData).length) return;
			let sku_array = [];
			Object.keys(this.goodsData).forEach(key => {
				let item = this.goodsData[key];
				sku_array.push({
					sku_id: item.sku_id,
					num: item.num
				});
			});
			let data = {
				sku_array: JSON.stringify(sku_array),
				create_time: this.orderData.create_time
			};
			if (this.memberInfo) data.member_id = this.memberInfo.member_id;

			this.$api.sendRequest({
				url: '/cashier/storeapi/cashierordercreate/cardcalculate',
				data: data,
				success: res => {
					if (res.code == 0) {
						Object.assign(this.orderData, res.data);
						// uni.setStorageSync('orderData', this.orderData);
						this.$forceUpdate();
					} else {
						this.$util.showToast({
							title: res.message
						});
					}
				}
			});
		},
		inc(data) {
			if (data.goods_type != '') {
				this.goodsData['sku_' + data.sku_id].num += 1;
			} else {
				if (data.num < data.stock) this.goodsData['sku_' + data.sku_id].num += 1;
			}
			this.calculation();
		},
		dec(data) {
			if (data.num > 1) {
				this.goodsData['sku_' + data.sku_id].num -= 1;
				this.calculation();
			}
		},
		deleteGoods(data) {
			delete this.goodsData['sku_' + data.sku_id];
			this.calculation();

			if (!Object.keys(this.goodsData).length) {
				this.orderData.goods_list = [];
				this.orderData.goods_num = 0;
				this.orderData.pay_money = 0;
			}
			uni.setStorageSync('orderData', this.orderData);
		},
		clearGoods() {
			this.goodsData = [];
			this.orderData.goods_list = [];
			this.orderData.goods_num = 0;
			this.orderData.pay_money = 0;
			this.goodsIds = [];
		},
		pay(type = '', callback) {
			if (!this.memberInfo) {
				if (this.$refs.selectMember) {
					this.pageActive = 'ShowMember';
					this.$refs.selectMember.open(() => {
						this.pageActive = 'ShowMemberAfter';
					});
					setTimeout(() => {
						this.$refs.selectMember.inputFocus = true;
					}, 200);
				}
				return false;
			}
			if (!Object.keys(this.goodsData).length || this.isRepeat) return;
			this.isRepeat = true;

			if (this.outTradeNo) {
				this.type = 'pay';
				if (type) this.$refs.payment.type = type;
				return;
			}

			this.pageActive = 'OrderCreate'; // 记录页面活跃值：创建订单

			let sku_array = [];
			Object.keys(this.goodsData).forEach(key => {
				let item = this.goodsData[key];
				sku_array.push({
					sku_id: item.sku_id,
					num: item.num
				});
			});
			let data = {
				sku_array: JSON.stringify(sku_array),
				remark: this.orderData.remark,
				create_time: this.orderData.create_time
			};
			if (this.memberInfo) data.member_id = this.memberInfo.member_id;

			this.$api.sendRequest({
				url: '/cashier/storeapi/cashierordercreate/cardcreate',
				data: data,
				success: res => {
					this.isRepeat = false;
					if (res.code == 0) {
						this.outTradeNo = res.data.out_trade_no;
						this.orderId = res.data.order_id;
						this.type = 'pay';
						if (type) this.$refs.payment.type = type;
						setTimeout(() => {
							if (callback) callback();
						}, 100)
					} else {
						this.$util.showToast({
							title: res.message
						});
					}
				}
			});
		},
		cancelPayment() {
			this.$api.sendRequest({
				url: '/cashier/storeapi/cashierorder/deleteorder',
				data: {
					order_id: this.orderId
				},
				success: res => {
					if (res.code == 0) {
						this.outTradeNo = '';
						this.orderId = 0;
						this.type = 'goods';
					} else {
						this.$util.showToast({
							title: res.message
						});
					}
				}
			});
		},
		paySuccess() {
			this.type = 'goods';
			this.wholeOrderCancel();
		},
		/**
		 * 整单取消
		 */
		wholeOrderCancel() {
			if (Object.keys(this.goodsData).length) {
				// 清除商品数据
				this.goodsData = {};
				this.calculation();
				if (this.orderData.order_id) {
					this.$refs.order.deleteOrder(this.orderData);
					this.orderData.order_id = 0;
				}
				// 清除订单数据
				this.orderData = {
					goods_num: 0,
					pay_money: 0,
					goods_list: [],
					remark: '',
					create_time: this.$util.timeFormat(parseInt(new Date().getTime() / 1000))
				};
				this.outTradeNo = '';
				this.orderId = 0;
			} else {
				this.$util.showToast({
					title: '当前没有订单'
				});
			}
		},
		toGoods() {
			this.type = 'goods';
		},
		/**
		 * 添加键盘监听事件
		 */
		addKeyDownEvent() {
			// #ifdef H5
			// 绑定监听事件
			window.addEventListener("keydown", this.listenerKeyDown, true);

			// 监听F1~F12，BACKSPACE
			window.POS_HOTKEY_CALLBACK = (control, code) => {
				this.posHotKeyCallback(code);
			};
			// #endif
		},
		/**
		 * 移除键盘监听事件
		 */
		removeKeyDownEvent() {
			// #ifdef H5
			window.removeEventListener("keydown", this.listenerKeyDown, true);

			delete window.POS_HOTKEY_CALLBACK;
			// #endif
		},
		listenerKeyDown(e) {
			var code = e.code;

			// console.log('KeyDown', this.type, code, this.pageActive, this.orderData, e);

			// 快捷支付，KeyN：付款码支付，KeyC：现金支付（cash），KeyW：微信支付（wechat），A：支付宝支付（alipay），KeyP：POS刷卡支付（POS）
			let letterCode = ['KeyN', 'KeyC', 'KeyW', 'KeyA', 'KeyP'];

			if (this.type != 'pay' && code == 'KeyM') {
				// 选择会员，键盘快捷键【M】
				if (this.$refs.selectMember) {
					this.pageActive = 'ShowMember';
					this.$refs.selectMember.open(() => {
						this.pageActive = 'ShowMemberAfter';
					});
				}
			} else if (this.pageActive == 'ShowMember') {
				// 打开会员弹出框

				this.memberCallback(code);

			} else if (this.pageActive == 'ShowMemberAfter') {
				// 活跃窗口：设置会员后

				if (code == 'Enter' || code == 'NumpadEnter') {
					this.pay('');
				}

			} else if (this.orderData.goods_num && this.pageActive == 'SelectGoodsAfter') {
				// 选择卡项商品后
				if (code == 'Enter' || code == 'NumpadEnter') {
					this.pay('');
				}

			} else if (this.pageActive == 'OrderCreate') {
				// 创建订单
				
				if (letterCode.indexOf(code) != -1) {
					// 快捷下单

					this.quickOrderCallback(code);

				} else {
					this.orderCreateCallback(code);
				}

			}

		},
		/**
		 * 监听键盘事件回调
		 * @param {Object} code
		 */
		posHotKeyCallback(code) {
			if (code == 'F2') {
				// 选择卡项

				if (this.type != 'pay') {
					this.toGoods();
					this.pageActive = 'SelectGoodsAfter';
				}

			} else if (code == 'F3') {
				// 选择会员

				if (this.type != 'pay') {
					this.showMember();
				}

			} else if (code == 'BACKSPACE') {
				// 退格键

				if (this.pageActive == 'OrderCreate') {
					if (this.$refs.payment) {
						if (this.$refs.payment.active == 'openMoneyPopup') {
							this.$refs.payment.deleteCode();
						}
					}
				}

			} else {
				// 触发左侧菜单按键回调
				this.menuTriggerKeyCodeCallBack(code);
			}
		},
		/**
		 * 打开会员弹出框 事件回调
		 * @param {string} code 按键代码
		 */
		memberCallback(code) {
			let selectMember = this.$refs.selectMember;

			// 选择会员，回车确认
			if (code == 'Enter' || code == 'NumpadEnter') {
				if (selectMember && selectMember.memberId && selectMember.active == 'SearchMember') {
					selectMember.getMemberInfo(selectMember.memberId, () => {
						this.pageActive = 'ShowMemberAfter';
					});
				}
			}
		},
		/**
		 * 快捷下单 事件回调
		 * @param {string} code 按键代码
		 */
		quickOrderCallback(code) {
			if (!this.orderData.goods_num) return;

			if (!this.$refs.payment) return;

			let payment = this.$refs.payment;

			// 不能存在操作
			if (payment.active) return;

			// 快捷支付，KeyN：付款码支付，KeyC：现金支付（cash），KeyW：微信支付（wechat），A：支付宝支付（alipay），KeyP：POS刷卡支付（POS）
			payment.hotKeyPay(code, this.type, () => {
				this.pay('', () => {
					payment.hotKeyPayCallback(code);
				});
			});
		},
		/**
		 * 订单创建 事件回调
		 * @param {string} code 按键代码
		 */
		orderCreateCallback(code) {
			if (!this.$refs.payment) return;

			let payment = this.$refs.payment;

			// console.log('创建订单', payment.active, payment.type, payment.paystatus);
			if (code == 'Escape') {
				// 取消支付，回到上一步，检测当前没有弹出框

				if (this.$refs.payment.active == '') {

					payment.cancelPayment();
					this.pageActive = 'SelectGoodsAfter';

				}
			} else if (payment.active == 'OpenMoneyPopup') {

				if (code == 'Enter' || code == 'NumpadEnter') {

					if (payment.moneyPopup.type == 'reduction') {
						// 减免金额

						payment.moneyPopupConfirm();

					} else if (payment.moneyPopup.type == 'cash') {
						// 现金支付

						payment.moneyPopupConfirm(() => {
							payment.confirm();
						});

					}

				} else if (code == 'NumpadDecimal') {

					payment.keydown('.');

				} else if (code.indexOf('Numpad') != -1) {

					var num = code.replace('Numpad', '')
					payment.keydown(num);


				} else if (code.indexOf('Digit') != -1) {

					var num = code.replace('Digit', '')
					payment.keydown(num);

				}

			} else if (code == 'Enter' || code == 'NumpadEnter') {

				if (payment.paystatus == 'success') {
					// 支付成功

					payment.paySuccess();
					this.pageActive = '';

				} else if (payment.active == 'RemarkPopup') {
					// 备注

					payment.remarkConfirm();

				} else if (payment.active == 'safeVerifyPopup') {
					// 使用付款码，出示付款码、验证手机号

					setTimeout(() => {
						// 打开付款码，设置焦点
						payment.scancodeFocus = true;
					}, 200);

					if (payment.safeVerifyType == 'payment_code') {

						payment.verifyPaymentCode({
							detail: {
								value: payment.paymentCode
							}
						});

					} else if (payment.safeVerifyType == 'sms_code') {

						payment.verifySmsCode({
							detail: {
								value: payment.smsCode
							}
						});

					}

				} else if (payment.active == 'thirdConfirm') {
					// 打开付款码，设置焦点

					setTimeout(() => {
						// 打开付款码，设置焦点
						payment.scancodeFocus = true;
					}, 200);

				} else if (payment.type == 'cash') {

					// 选择【现金支付】方式，打开现金支付弹出框
					if (payment.active == '') {
						payment.switchPayType(payment.type);
					}

				} else if (payment.type != 'third') {
					payment.confirm();
				} else if (payment.active == '') {
					// 付款码/扫码枪

					payment.thirdConfirm();
					setTimeout(() => {
						// 初次打开，设置焦点
						payment.scancodeFocus = true;
					}, 200);

				}
			}
		}
	},
	watch: {
		memberInfo: function(nVal) {
			this.calculation();
		}
	}
}